#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"

int p[36][2];

void prime_fork(int last, int from) {
    if (fork() == 0) {
        int prime, now;
        now = -1; prime = -1;
        if (last != -1) {
            close(p[last][0]);
        }
        close(p[from][1]);
        while (read(p[from][0], &now, 4)) {
            if (prime == -1) {
                prime = now;
                pipe(p[prime]);
                prime_fork(from, prime);
                close(p[prime][0]);
                printf("prime %d\n", prime);
                continue;
            } else {
                if (now % prime == 0) {
                    continue;
                } else {
                    write(p[prime][1], &now, 4);
                }
            }
        }
        if (prime != -1) {
            close(p[prime][1]);
            wait(0);
        }
        exit(0);
    }
    return;
}

int main() {
    pipe(p[1]);
    prime_fork(-1, 1);
    close(p[1][0]);
    for (int i = 2; i <= 35; i++) {
        write(p[1][1], &i, 4);
    }
    close(p[1][1]);
    wait(0);
    exit(0);
}